package com.peak.distribution.config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.util.matcher.RequestMatcher;

import com.google.common.collect.Lists;
import com.peak.distribution.config.security.SessionAuthenticationFailureHandler;
import com.peak.distribution.config.security.SessionAuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private SessionAuthenticationSuccessHandler successHandler;
	
	@Autowired
	private SessionAuthenticationFailureHandler failureHandler;
	
	/**
	 * 校验登录用户名和密码
	 * 
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	/**
	 * 配置
	 * 
	 * @param http
	 * @throws Exception
	 */
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		//.antMatchers(HttpMethod.POST, "/agent/list", "/agent/audit/*").hasAnyRole("ADMIN")
		.anyRequest().authenticated()
		.and()
			.rememberMe()
			.rememberMeParameter("rememberme")
			.tokenValiditySeconds(1209600)//2周
			.userDetailsService(userDetailsService)
		.and()
			.sessionManagement()
			.maximumSessions(1)
			.expiredUrl("/login?expired=true")
		.and()
		.and()
			.formLogin()
			.loginPage("/login")
			.failureUrl("/login?error=true")
			.loginProcessingUrl("/login")
			.successHandler(successHandler)
			.failureHandler(failureHandler)
			.permitAll()
		.and()
			.logout()
			.logoutUrl("/logout")
			.logoutSuccessUrl("/login")
			.permitAll()
		.and()
			.exceptionHandling()
			.defaultAuthenticationEntryPointFor(new Http403ForbiddenEntryPoint(), new RequestMatcher() {
	
					@Override
					public boolean matches(HttpServletRequest request) {
						return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))
								|| request.getHeader("Accept") != null && request.getHeader("Accept").contains("application/json");
					}
				})
		.and()
			.csrf().disable();
	}

	/**
	 * 可以匿名访问的地址，使用此地址的请求是无法获取当前登录用户的
	 */
	public void configure(WebSecurity web) throws Exception {
		// 静态资源
		List<String> urls = Lists.newArrayList("/js/**", "/css/**", "/html/**", "/images/**", "/error", "/error/**");
		// 获取图片验证码
		urls.add("/captcha/get/*");
		// 发送短信验证码
		urls.add("/agent/send/sms");
		// 验证短信验证码有效性
		urls.add("/agent/check/mobile/code");
		// 重置密码
		urls.add("/agent/reset/password");
		// 推荐添加代理商相关
		urls.add("/recommend/*");
		urls.add("/agent/recommend/*");
		urls.add("/agent/recommend/sub/add");
		web.ignoring().antMatchers(urls.toArray(new String[urls.size()]));
	}
}
